package dancrawler.client;

import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import java.net.UnknownHostException;

/**
 *
 */
public class ConnectDialog extends JDialog implements ActionListener {

    private JTextField addressField = new JTextField(10);
    private JTextField portField = new JTextField(5);
    private JButton connectButton = new JButton("Connect");
    private JButton cancelButton = new JButton("Cancel");
    private String address = "";
    private int port = 1881;

    public ConnectDialog(Frame owner) throws UnknownHostException {
        super(owner);
        this.address = InetAddress.getLocalHost().toString().split("/")[1];
        addressField.setText(address);
        portField.setText("1881");
        this.setModalityType(ModalityType.APPLICATION_MODAL);
        this.setSize(300, 100);
        this.setLocationRelativeTo(owner);
        FlowLayout layout = new FlowLayout();
        this.setLayout(layout);
        this.add(new JLabel("Address"));
        this.add(addressField);
        this.add(new JLabel("Port"));
        this.add(portField);
        this.add(connectButton);
        this.add(cancelButton);
        connectButton.addActionListener(this);
        cancelButton.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent ev) {
        if(ev.getSource() == cancelButton)
        {
            address = "";
            this.setVisible(false);
        }
        else if(ev.getSource() == connectButton)
        {
            try{
            port = Integer.parseInt(portField.getText());
            address = addressField.getText();
            this.setVisible(false);
            }catch(NumberFormatException e)
            {

            }
            if(port <= 0)
            {
                address = "";
                port = 0;
                JOptionPane.showMessageDialog(this, "Port must be a positive integer");
            }

        }
    }

    public static InetSocketAddress getAddress(Frame owner) throws UnknownHostException
    {
        ConnectDialog cd = new ConnectDialog(owner);
        cd.setVisible(true);
        cd.dispose();
        if(cd.address.equals("") || cd.port == 0)
        {
            return null;
        }
        return new InetSocketAddress(cd.address, cd.port);
    }
}
